/*
 *  Copyright (C) 2010 Glauco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.balisunrise.common.defaults;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import org.balisunrise.application.Application;
import org.balisunrise.common.Action;
import org.balisunrise.common.ActionMap;
import org.balisunrise.common.EntityField;
import org.balisunrise.common.Event;
import org.balisunrise.common.VisualEntity;
import org.balisunrise.common.abstracts.AbstractAction;

/**
 * Ação onde a instância do mapa de ações é conhecida.
 *
 * @author Glauco
 */
public class DirectAction extends AbstractAction implements Action{

    /**
     * Instância do Mapa de ações
     */
    Object map;

    public DirectAction(Object map, Method method, boolean withParm) {
        this.map = map;
        setMethod(method);
        setWithParm(withParm);
    }

    public void setMap(Object map) {
        this.map = map;
    }

    public Object getMap() {
        return map;
    }

    @Override
    public void perform(Event evt) {

        if(map == null){
            String msg = "Action can not be performed." +
                    " MAP IS NULL!" +
                    " METHOD: " + method.toString();
            Application.get().getLogger().log(Level.SEVERE, msg, null);
            return ;
        }

        if(map instanceof ActionMap){
            ActionMap aMap = (ActionMap) map;
            if (owner instanceof EntityField)
                aMap.addEntityField((EntityField) owner);
            VisualEntity ve = VEAUtil.getVisualEntity(owner);
            if(ve != null)
                aMap.addVisualEntity(ve);
        }

        try{
            if(isWithParm())
                method.invoke(map, evt);
            else
                method.invoke(map);
        } catch (IllegalAccessException ex) {
            log(map, ex);
        } catch (IllegalArgumentException ex) {
            log(map, ex);
        } catch (InvocationTargetException ex) {
            log(map, ex);
        }
    }

    private void log(Object map, Exception ex){
        String msg = "Action can not be performed." +
                    " MAP: " + map.toString() +
                    " METHOD: " + method.toString();
        Application.get().getLogger().log(Level.SEVERE, msg, ex);
    }
}
